﻿using DevExpress.Data.Filtering;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace Inaction.UI.Extensions.ControlExtensions
{
    public static class GridLookUpEditExtender
    {
        public static void Extend(Control c, Form form)
        {
            if (!(c is GridLookUpEdit)) return;
            var gLue = c as GridLookUpEdit;
            gLue.Popup += (sender, e) =>
            {
                form.BeginInvoke(new System.Windows.Forms.MethodInvoker(delegate
                {
                    FilterLookup(gLue);
                }));
            };
            gLue.EditValueChanging += (sender1, e1) =>
            {
                form.BeginInvoke(new System.Windows.Forms.MethodInvoker(delegate
                {
                    FilterLookup(gLue);
                }));
            };
        } 
        static void FilterLookup(GridLookUpEdit glue)
        {
            if (glue.Properties.View.VisibleColumns.Count == 0) return;
            var gridView = glue.Properties.View as GridView;
            gridView.ClearColumnsFilter();
            var firstFieldName = glue.Properties.View.VisibleColumns[0].FieldName;
            FieldInfo fi = gridView.GetType().GetField("extraFilter", BindingFlags.NonPublic | BindingFlags.Instance);
            BinaryOperator op = new BinaryOperator(firstFieldName, glue.AutoSearchText + "%", BinaryOperatorType.Like);
            string filterCondition = new GroupOperator(op).ToString();
            fi.SetValue(gridView, filterCondition);
            MethodInfo method = gridView.GetType().GetMethod("ApplyColumnsFilterEx", BindingFlags.NonPublic | BindingFlags.Instance);
            method.Invoke(gridView, null);
        }
    }
}
